/**
 * Licensed to Jasig under one or more contributor license
 * agreements. See the NOTICE file distributed with this work
 * for additional information regarding copyright ownership.
 * Jasig licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file
 * except in compliance with the License. You may obtain a
 * copy of the License at:
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on
 * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package me.thinkjet.sso.client.filter;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.Filter;
import javax.servlet.FilterConfig;

import me.thinkjet.sso.client.util.CommonUtils;

public abstract class AbstractConfigurationFilter implements Filter {

    private boolean ignoreInitConfiguration = false;

    protected final String getPropertyFromInitParams(
	    final FilterConfig filterConfig, final String propertyName,
	    final String defaultValue) {
	final String value = filterConfig.getInitParameter(propertyName);

	if (CommonUtils.isNotBlank(value)) {
	    return value;
	}

	final String value2 = filterConfig.getServletContext()
		.getInitParameter(propertyName);

	if (CommonUtils.isNotBlank(value2)) {
	    return value2;
	}
	InitialContext context;
	try {
	    context = new InitialContext();
	} catch (final NamingException e) {
	    return defaultValue;
	}

	final String shortName = this.getClass().getName()
		.substring(this.getClass().getName().lastIndexOf(".") + 1);
	final String value3 = loadFromContext(context, "java:comp/env/cas/"
		+ shortName + "/" + propertyName);

	if (CommonUtils.isNotBlank(value3)) {
	    return value3;
	}

	final String value4 = loadFromContext(context, "java:comp/env/cas/"
		+ propertyName);

	if (CommonUtils.isNotBlank(value4)) {
	    return value4;
	}

	return defaultValue;
    }

    protected final boolean parseBoolean(final String value) {
	return ((value != null) && value.equalsIgnoreCase("true"));
    }

    protected final String loadFromContext(final InitialContext context,
	    final String path) {
	try {
	    return (String) context.lookup(path);
	} catch (final NamingException e) {
	    return null;
	}
    }

    public final void setIgnoreInitConfiguration(boolean ignoreInitConfiguration) {
	this.ignoreInitConfiguration = ignoreInitConfiguration;
    }

    protected final boolean isIgnoreInitConfiguration() {
	return this.ignoreInitConfiguration;
    }
}
